﻿
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web;
using Microsoft.SharePoint.Utilities;

/*
Developed By: Sujeet Kumar
Developed On: July 2011
Description: This code Creating a project Site by getting title and description.
*/
namespace SiteProjects.Create_Project
{
    public partial class Create_ProjectUserControl : UserControl
    {
        SPWeb webSite;       
        string CurrentUserEmail;
        protected void Page_Load(object sender, EventArgs e)
        {  
            CurrentUserEmail = SPContext.Current.Web.CurrentUser.Email;
        }

        /// <summary>
        /// Clear the controls if the cancel button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imbCancel_Click(object sender, ImageClickEventArgs e)
        {
            txtCreateProjectName.Text = "";
            txtDescription.Text = "";
            lblMessage.Text = "";
        }

        /// <summary>
        /// Following event  will create a new Project site.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imbCreateProject_Click(object sender, ImageClickEventArgs e)
        {
            string userName = string.Empty;
            string accountName = string.Empty;            
            string currentUrl = Request.Url.ToString();
            string title = txtCreateProjectName.Text.ToLower().Trim();
            title = title.Replace(" ", "_");
            string physicalPath = Server.MapPath("/_layouts/CreateProject/LaTrobeProjectV6.wsp");
            string TemplateName = "LaTrobeProjectV6.wsp";
            string urlName = "/projects/" + title;
            string currentAccount = string.Empty;          
            string currentLogin = this.Context.User.Identity.Name;            
            try
            {
                SPUserInfo objInfo = new SPUserInfo();
                SPSite mySite = SPContext.Current.Site;
                // Microsoft.SharePoint.SPWeb webSite = Microsoft.SharePoint.SPContext.Current.Web;
                webSite = SPContext.Current.Web;
                SPWeb web = SPControl.GetContextWeb(Context);
                SPUser sUser = web.CurrentUser;
                currentUrl = webSite.Url;
                userName = this.Context.User.Identity.Name;                 
                currentAccount = sUser.LoginName;               
                // webSite.Url.Insert(webSite.Url., urlName);
                accountName ="i:" + userName;
                //Condition check to fetch the junk value in the sharepoint variable.
                if (userName.ToString().Contains("f|sqlmember|"))
                {
                    string indexUser = userName.ToString().Substring(objInfo.LoginName.ToString().LastIndexOf('|'));
                    userName = indexUser.Trim('|').Trim().ToString();
                }
                else
                {
                   if (userName.ToString().Contains("0#.w|"))
                       userName = userName.Replace("0#.w|", "");
                    else
                       userName = userName.Replace("i:0#.w|", "");
                    //userName = objEntity.Key;
                  //  userName = webSite.CurrentUser.LoginName.ToString();
                }
                //userName = userName.Replace("i:0#.w|", "");
                int pos = userName.IndexOf("\\");
                if (pos > 0)
                    userName = userName.Substring(pos + 1);
                SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                bool siteExists = SiteExists();
                if (!siteExists)

                {
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H3>Creating project site</H3></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Your project site is being created  and will be mounted to the RDS directory share. This can take a while, please wait</H4></DIV>";
                    lop.Begin();
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = webApp.Sites.Add("/projects/" + title, txtCreateProjectName.Text, txtDescription.Text, 1033, null, userName, userName, null))
                        {
                            SPWeb rootWeb = site.RootWeb;
                            // Get Solutions Gallery    
                            SPDocumentLibrary solutions = (SPDocumentLibrary)site.GetCatalog(SPListTemplateType.SolutionCatalog);
                            // Upload Solution File with the Web Template    
                            //SPFile solutionFile = solutions.RootFolder.Files.Add("ProjectTest.wsp", File.ReadAllBytes(@"C:\ProjectTest.wsp"));
                            SPFile solutionFile = solutions.RootFolder.Files.Add(TemplateName, File.ReadAllBytes(physicalPath));
                            // Activate Solution    
                            SPUserSolution solution = site.Solutions.Add(solutionFile.Item.ID);
                            // Activate Features    
                            Guid solutionId = solution.SolutionId;
                            // Activate Site Collection Features    
                            SPFeatureDefinitionCollection siteFeatures = site.FeatureDefinitions;
                            var features = from SPFeatureDefinition f in siteFeatures
                                           where f.SolutionId.Equals(solutionId)
                                           && f.Scope == SPFeatureScope.Site
                                           select f;
                            foreach (SPFeatureDefinition feature in features)
                            {
                                site.Features.Add(feature.Id, false, SPFeatureDefinitionScope.Site);
                            }
                            // Get Web Template    
                            SPWebTemplateCollection webTemplates = site.RootWeb.GetAvailableWebTemplates(1033);
                            SPWebTemplate webTemplate = (from SPWebTemplate t in webTemplates
                                                         where t.Title == "LaTrobeProjectV6"
                                                         select t).FirstOrDefault();
                            if (webTemplate != null)
                            {
                                site.RootWeb.ApplyWebTemplate(webTemplate.Name);
                            }
                            //Code to create default groups on newly created site (i.e. Owner, Member, and visitors groups). 
                            site.RootWeb.CreateDefaultAssociatedGroups(accountName, accountName, title);

                        }
                    });

                    string msgWithUrl = "Your Project site is created successfully the url is:   ";
                    msgWithUrl = msgWithUrl + currentUrl + urlName;
                    bool isMail=SendMail(userName); 
                    lop.End(SPContext.Current.Site.Url + "/default.aspx", Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    Response.Redirect(SPContext.Current.Site.Url + "/default.aspx", false);
                }
                else
                {
                    lblMessage.Text = "Your Project name is already used for another project, please change the name and try again";
                    lblMessage.ForeColor = Color.Red;
                }

            }
            catch (Exception ex)
            {
                lblMessage.Text = "Your Project site could not be created successfully, please try again later!";
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = ex.Message;
            }
            finally
            {
                

            }

         
              
        }

        /// <summary>
        /// Check the requested name for project site is already exist or not.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool SiteExists()
        {
           // FindUserInfo();
            bool IsExist = false;
            string title = txtCreateProjectName.Text.ToLower().Trim();
            title = title.Replace(" ", "_");
            string site = "projects/" + title;
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
                    SPSiteCollection siteCollections = webApplication.Sites;

                    for (int i = 0; i < siteCollections.Count; i++)
                    {
                        //Check site name is exist in collection                   
                        if (site == siteCollections.Names[i].ToLower().Trim())
                        {
                            //if site exist then return true value
                            IsExist = true;
                            break;
                        }
                    }
                });
            }
            catch (Exception ex)
            { lblMessage.Text = ex.Message; }
            return IsExist;
        }


        /// <summary>
        /// Send a mail 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool SendMail(string userName)
        {
            bool IsSuccess = false;
            string subjectEmail = "A New Project Site Is Created Successfully";
            string strBody = string.Empty;
            string mailBody = string.Empty;
            string strFilePath = Server.MapPath("~/_layouts/CreateProject/CreateProjectMail.htm");
            if (CurrentUserEmail != "")
            {
                if (File.Exists(strFilePath))
                {
                    StreamReader Sr = new StreamReader(strFilePath);
                    strBody = Sr.ReadToEnd();
                    Sr.Dispose();
                    strBody = strBody.Replace("@@@@user", userName.Trim());
                    strBody = strBody.Replace("@@@@email", CurrentUserEmail.Trim());
                    strBody = strBody.Replace("@@@@projectName", txtCreateProjectName.Text.ToString());
                   
                }
                mailBody = strBody;
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                     {
                         using (SPSite site = new SPSite(
                           SPContext.Current.Site.ID,
                           SPContext.Current.Site.Zone))
                         {
                             using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                             {
                                 IsSuccess = SPUtility.SendEmail(web, true, false,
                                                            CurrentUserEmail,
                                                            subjectEmail,
                                                            mailBody);
                             }
                         }
                     });
                   // IsSuccess = SPUtility.SendEmail(webSite, true, true, CurrentUserEmail, subjectEmail, mailBody);
                   
                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.Message;
                    IsSuccess = false;
                }                
            }
            else
            {
                lblMessage.Text = "The Author have not mentioned his Email";
                IsSuccess = false;

            }
            return IsSuccess;
        }
           


    }
}
